/**
 * chenuu.com
 * 
 * @author  zhaoxu.com@gmail.com
 * @created 2012-11-17
 */
package com.chenuu.webapp.tools;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.context.Context;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.Toolbox;
import org.apache.velocity.tools.ToolboxFactory;
import org.apache.velocity.tools.config.XmlFactoryConfiguration;
import org.apache.velocity.tools.view.ViewToolContext;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.servlet.view.velocity.VelocityLayoutView;

/**
 *
 */
public class VelocityToolbox2View extends VelocityLayoutView implements ResourceLoaderAware {

	private ResourceLoader resourceLoader;

	/* (non-Javadoc)
	 * @see org.springframework.context.ResourceLoaderAware#setResourceLoader(org.springframework.core.io.ResourceLoader)
	 */
	@Override
	public void setResourceLoader(ResourceLoader arg0) {
		this.resourceLoader = arg0;
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.view.velocity.VelocityToolboxView#createVelocityContext(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected Context createVelocityContext(Map<String, Object> model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ViewToolContext viewToolContext = new ViewToolContext(getVelocityEngine(), request,
				response, getServletContext());
		String urlpath = getToolboxConfigLocation();
		if (urlpath != null) {
			urlpath = resourceLoader.getResource(urlpath).getFile().getAbsolutePath();
			XmlFactoryConfiguration factoryConfiguration = new XmlFactoryConfiguration();
			factoryConfiguration.read(urlpath);
			ToolboxFactory factory = factoryConfiguration.createFactory();
			Toolbox toolbox = factory.createToolbox(Scope.SESSION);
			viewToolContext.addToolbox(toolbox);
			toolbox = factory.createToolbox(Scope.APPLICATION);
			viewToolContext.addToolbox(toolbox);
			toolbox = factory.createToolbox(Scope.REQUEST);
			viewToolContext.addToolbox(toolbox);

			super.setToolAttributes(viewToolContext.getToolClassMap());
		}
		viewToolContext.putAll(model);
		return viewToolContext;
	}

}
